#!/bin/sh
set -e

# Requirements:
# sudo apt-get install dpkg-dev qtdeclarative5-dev debhelper qt5-default build-essential libqt5opengl5-dev

# Any extra arguments to compile here
cc_args=

tmpdir=`mktemp -d`
trap "rm -rf $tmpdir" EXIT HUP INT QUIT TERM

cd `dirname $0`
topdir=`pwd`
appname=`basename "$topdir"`
cp -a ./app "$tmpdir"
cp -a ./backend "$tmpdir"
cp -a ./*.json "$tmpdir"
cp -a ./*.pro* "$tmpdir"
cd "$tmpdir"

arch=`dpkg-architecture | grep DEB_BUILD_ARCH= | cut -d '=' -f 2`
# dumb, but this whole script is dumb
cc=linux-g++
if [ "$arch" = "amd64" ]; then
    cc=linux-g++-64
fi
/usr/lib/i386-linux-gnu/qt5/bin/qmake "$appname".pro -r -spec $cc $cc_args
make

echo "Adjust the manifest to include: \"architecture\": \"$arch\","
sed -i "s/^{/{\\n    \"architecture\": \"$arch\",/g" ./manifest.json

echo "Adjust the desktop file"
name=`grep '"name"' ./manifest.json | sed 's/.*: "//g' | cut -d '"' -f 1`
version=`grep '"version"' ./manifest.json | sed 's/.*: "//g' | cut -d '"' -f 1`
sed -i "s#^Exec=.*#Exec=/usr/bin/qmlscene -I backend/modules app/${appname}.qml#g" ./app/${appname}.desktop

# now clean it up
echo "Clean out install dir"
find "$tmpdir" -name "*.pro" -exec rm -f {} \;
find "$tmpdir" -name "*.pro.user" -exec rm -f {} \;
find "$tmpdir" -name "Makefile" -exec rm -f {} \;
rm -rf "$tmpdir"/app/tests "$tmpdir"/backend/tests
rm -f "$tmpdir"/backend/modules/${appname}/*.cpp
rm -f "$tmpdir"/backend/modules/${appname}/*.h
rm -f "$tmpdir"/backend/modules/${appname}/*.o

cd "$topdir"
echo "Running: click build $tmpdir"
click build "$tmpdir"

echo ""
echo "Install with: sudo click install --force-missing-framework --user=$USER ./${name}_${version}_${arch}.click"
